package com.dunqi.gpm.cangxi.home.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.dunqi.gpm.cangxi.common.util.CommonUtil;

/**
 * Created by 空 on 2017/11/17 0017.
 */

public class CircleTextView extends View {

    String text = "";

    int bgColor = Color.RED;
    int textColor = Color.WHITE;
    int textsize = 12;

    private int leading;
    private int textWidth;
    private Paint paint;
    private Paint paint_bg;
    private Paint.FontMetrics metrics;

    public CircleTextView(Context context) {
        this(context, null);
    }

    String demoText = "99";

    public CircleTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(textColor);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        paint.setTextSize(CommonUtil.dip2px(textsize));

        paint_bg = new Paint();
        paint_bg.setStyle(Paint.Style.FILL);
        paint_bg.setAntiAlias(true);
        paint_bg.setColor(bgColor);

        metrics = paint.getFontMetrics();
        textWidth = (int) (metrics.bottom - metrics.top);
        leading = (int) (metrics.leading - metrics.top);
    }


    public void setText(String text) {
        this.text = text;
        postInvalidate();
    }

    public void setBgColor(int color) {
        bgColor = color;
        paint_bg.setColor(bgColor);
        postInvalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = 2 * getPaddingLeft() + textWidth;

        setMeasuredDimension(width, width);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int height = getHeight();
        Path clipPath = new Path();
        clipPath.addRoundRect(new RectF(0, 0, height, height), height / 2, height / 2, Path.Direction.CW);
        canvas.clipPath(clipPath);

        canvas.drawCircle(height / 2, height / 2, height / 2, paint_bg);
        if (text.length() == 1) {
            canvas.drawText(text, getPaddingLeft() + textWidth / 4, getPaddingLeft() + leading, paint);
        }

        if (text.length() == 2) {
            canvas.drawText(text, getPaddingLeft() + (int) (metrics.bottom - metrics.leading) / 2, getPaddingLeft() + leading, paint);
        }


    }
}
